package com.douyin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyin.entity.User;
import com.douyin.mapper.UserMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    public User findByOpenid(String openid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);
        return getOne(queryWrapper);
    }

    public User createOrUpdateUser(String openid, String nickname, String avatarUrl) {
        User user = findByOpenid(openid);
        
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setNickname(nickname);
            user.setAvatarUrl(avatarUrl);
            user.setStatus(1);
            user.setRegisterTime(LocalDateTime.now());
            user.setTotalParseCount(0);
            save(user);
        } else {
            user.setNickname(nickname);
            user.setAvatarUrl(avatarUrl);
            user.setLastLoginTime(LocalDateTime.now());
            updateById(user);
        }
        
        return user;
    }

    public void incrementParseCount(Long userId) {
        User user = getById(userId);
        if (user != null) {
            user.setTotalParseCount(user.getTotalParseCount() + 1);
            updateById(user);
        }
    }

    public boolean isUserActive(Long userId) {
        User user = getById(userId);
        return user != null && user.getStatus() == 1;
    }

    public User findById(Long userId) {
        return getById(userId);
    }

    public User updateUserProfile(Long userId, String nickname, String avatarUrl) {
        User user = getById(userId);
        if (user != null) {
            user.setNickname(nickname);
            user.setAvatarUrl(avatarUrl);
            updateById(user);
        }
        return user;
    }
}